package com.vdongchina.miniapp.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Objects;

/**
 * Copyright (C)
 * FileName: LoginStatSign
 * Author:   maokai
 * Date:     2021/8/16 13:56
 * Description: 登录签名
 */
public class LoginStatSign {
    public static final String SIGN_METHOD = "SHA-256";


    public static String digest(Object object, String sessionKey) {
        String plainText = messageData(object);
        // 获取指定摘要算法的messageDigest对象
        MessageDigest messageDigest = null;
        try {
            //此处的sha代表SHA-256
            messageDigest = MessageDigest.getInstance(SIGN_METHOD, sessionKey);
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            e.printStackTrace();
            return "";
        }
        // 调用digest方法，进行加密操作
        byte[] cipherBytes = messageDigest.digest(plainText.getBytes());
        return encodeHexString(cipherBytes);
    }

    public static String messageData(Object object) {
        if (Objects.isNull(object)) {
            return "";
        }
        String dataJson = JsonUtils.toJson(object);

        return dataJson;
    }

    private static String encodeHexString(byte[] md5Bytes) {
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
